import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
  Table,
  Card,
  PaginationProps,
  Button, Modal, Form, Input, InputNumber, Message, Descriptions
} from '@arco-design/web-react';
import {  IconPlus, IconSearch } from '@arco-design/web-react/icon';
import useLocale from '@/utils/useLocale';
import styles from '@/pages/list/search-table/style/index.module.less';
import '@/pages/list/search-table/mock';
import locale from '@/pages/list/search-table/locale';
import api from '@/apis';
import getColumns from '@/pages/function/user/constant';
import Subscription from '@/pages/function/subscriptions';
import dayjs from 'dayjs';

function SearchTable() {
  const t = useLocale(locale);
  const childRef = useRef();

  const tableCallback = async (record, type) => {
    if (type === 'delete'){
      if (record.is_admin) {
        return Message.error("不可删除管理员")
      }
      Modal.confirm({
        title: '危险操作',
        content:
          '确认是否删除？',
        okButtonProps: {
          status: 'danger',
        },
        onOk: () => {
          api.delete('/api/v2/users/' + record.id).then((res) => {
            Message.info(res.data.message)

          }).catch(
            err => Message.error(err)
          ).finally(
            () => {
              fetchData()
            }
          )
        },
      });
    } else if (type === 'view_emails') {
      Modal.confirm({
        title: '查看邮件',
        content: record.emails.map(v => v.email),
      })
    } else if (type === 'view_logs') {
      api.get('/api/v2/users/' + record.id + "/point_logs").then((res) => {
        const point_logs = res.data.data.list
        Modal.confirm({
            title: '查看日志',
            content: (
              <ul>
                {point_logs.map((v, i) => (
                  <li key={i}>
                    原因:{v.reason} 发生时间 {v.created_at}<br/>分值变动: {v.points_change}
                  </li>
                ))}
              </ul>
            )
        });
      })
    }  else if (type === 'view_subs') {
      setShowSubModal(true);
      console.log(record.subscriptions?.map(v=>v.id))
      setUpdateUser(record)
      // api.get('/api/v2/users/' + record.id + "/subscriptions").then((res) => {
      //   const point_logs = res.data.data
      //   console.log(point_logs)
      //
      // Modal.confirm({
      //     title: '查看订阅',
      //     content: (
      //       <ul>
      //         {point_logs.map((v, i) => (
      //           <li key={i}>
      //             {v.name} : {v.description}
      //           </li>
      //         ))}
      //       </ul>
      //     )
      //   });
      // })
    } else if (type === 'edit') {
      // setShowSubModal(true);
      setCurUser({...record, email: record.emails[0].email})
      setIsEdit(true)
      setShowModal(true)
    } else if (type === 'view'){
      setDetailUser([
        {label: '用户名', value: record.username},
        {label: '邮箱', value: record.emails.map(v => v.email).join(",")},
        {label: '积分', value: record.points},
        {label: '创建时间', value: dayjs(record.created_at).format("YYYY-mm-dd")},
        {label: '关注订阅', value: record.subscriptions.map(v => v.name).join(",")},
        // {label: '积分日志', value: record.points_log},
      ])
      setShowDetailModal(true)
    }else{
      Message.error("功能暂未实现！")
    }
  };

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true
  });
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [showSubModal, setShowSubModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectSubs, setSelectSubs] = useState([]);
  const [updateUser, setUpdateUser] = useState([]);
  const [detailUser, setDetailUser] = useState([]);
  const [formParams, setFormParams] = useState({});
  const [curUser, setCurUser] = useState({
    username: '',
    password: '',
    email: '',
    points: 0
  });
  const columns = useMemo(() => getColumns(tableCallback), [t]);
  const formRef = useRef()
  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    api
      .get('/api/v1/admin/users/', {
        params: {
          page: current,
          num: pageSize,
          ...formParams
        }
      })
      .then((res) => {
        setData(res.data.data.list);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: res.data.data.total
        });
        setLoading(false);
      });
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize
    });
  }

  function handleSearch(params) {
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
    fetchData();
  }
  const onUpdate = (selectIds) => {
    setSelectSubs(selectIds);
  }
  const editSubsWithUser = () => {
    api.post(`/api/v2/users/${updateUser?.id}/subscriptions`,
      {subscription_ids: selectSubs}).then(res => {
      Message.info(res.data.message)
      setShowSubModal(false)
      fetchData()
    }).catch(
      err => Message.error(err)
    )
  }
  const handleSubmit = async () => {
    api.post('/api/v1/admin/users/', formRef.current.getFields()).then((res) => {
      const status = res?.data.status
      if (status === 'success'){
        Message.success(res?.data.message)
        fetchData()
        setShowModal(false)
      }
    }).catch(err => {
      Message.error(err)
    })
  }
  const handleEditSubmit = async () => {
    api.put('/api/v2/users/' + curUser.id, formRef.current.getFields()).then((res) => {
      const status = res?.data.status
      if (status === 'success'){
        Message.success(res?.data.message)
        fetchData()
        setShowModal(false)
      }
    }).catch(err => {
      Message.error(err)
    })
  }
  return (
    <Card title={t['menu.list.searchTable']} extra={
      <div className={styles.spaces_2}>
        <Button type="primary" icon={<IconSearch />} onClick={fetchData}>
          搜索
        </Button>
        <Button type="primary" icon={<IconPlus />}
                onClick={() => {
                  setShowModal(true);
                }}>
          {t['searchTable.operations.add']}
        </Button>
      </div>
    }>
      <Table
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
      />
      {showModal && <Modal title={isEdit ? "修改" : "添加"}
             visible={showModal}
             hideCancel={true}
             footer={null}
             onCancel={() => {setShowModal(false)}}
      >
        <Form ref={formRef} initialValues={curUser}>
          <Form.Item
            label="用户名"
            field="username"
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="密码"
            field="password"
          >
            <Input></Input>
          </Form.Item>
          <Form.Item
            label="积分"
            rules={[{ type: 'number', required: true }]}
            field="points"
          >
            <InputNumber></InputNumber>
          </Form.Item>
          <Form.Item
            label="邮箱"
            rules={[{ type: 'email', required: true }]}
            field="email"
          >
            <Input></Input>
          </Form.Item>
          <Button
            type="primary"
            onClick={async () => {
              if (formRef.current) {
                try {
                  await formRef.current.validate();
                  isEdit ? await handleEditSubmit() : await handleSubmit()
                  // Message.info('校验通过，提交成功！');
                } catch (_) {
                  console.error(formRef.current.getFieldsError());
                  Message.error('校验失败，请检查字段！');
                }
              }
            }}
            loading={loading}
            size="large"
          >
            {isEdit ? '保存修改' : '提交'}
          </Button>
        </Form>
      </Modal>}
      { showSubModal && <Modal style={{width: "90%"}} visible={showSubModal} onOk={() => editSubsWithUser()} onCancel={() => setShowSubModal(false)}>
        <Subscription ref={childRef} choose={true} onUpdate={onUpdate} initChecks={updateUser?.subscriptions.map(v => v.id)}></Subscription>
      </Modal>}
      { showDetailModal && <Modal visible={showDetailModal} footer={null}
                                  onCancel={() => {setShowDetailModal(false)}}>
        <Descriptions
          column={1}
          title='User Info'
          data={detailUser}
          labelStyle={{ textAlign: 'right', paddingRight: 36 }}
        />
      </Modal>}
    </Card>
  );
}

export default SearchTable;
